package com.yuri.news.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.yuri.news.entity.Depa;
import com.yuri.news.entity.User;
import com.yuri.news.jpa.DepaRepository;
import com.yuri.news.jpa.UserRepository;
import com.yuri.news.service.DepaService;

@Service
public class DepaServiceImpl implements DepaService {
	@Autowired
	DepaRepository depaRepository;
	@Autowired
	UserRepository userRepository;

	@Override
	public Depa saveDepa(Depa depa) {
		return depaRepository.save(depa);
	}

	@Override
	public Boolean deleteDepa(Long id) {
		Boolean flag = false;
		Optional<Depa> optional = depaRepository.findById(id);

		if (optional.isPresent()) {
			// 获得要删除部门的名字
			String depaName = depaRepository.findById(id).get().getDepaName();

			List<Depa> depas = depaRepository.findDepaAll(id);
			// 将该部门下的所有部门的上级部门设置为空
			for (int i = 0; i < depas.size(); i++) {
				depas.get(i).setUpDepa(null);
				depaRepository.save(depas.get(i));
			}
			// 将该部门下的所有用户的部门清空
			// 查询该部门下的所有有效用户
			List<User> users = userRepository.findByDepaName(depaName, true);
			// 添加该部门下的无效用户
			users.addAll(userRepository.findByDepaName(depaName, false));
			for (int i = 0; i < users.size(); i++) {
				users.get(i).setDepa(null);
				userRepository.save(users.get(i));
			}
			// 删除该部门
			depaRepository.deleteById(id);

			flag = true;
		}
		return flag;
	}

	@Override
	public Boolean updateDepa(Depa depa) {
		Boolean flag = false;

		Optional<Depa> optional = depaRepository.findById(depa.getId());

		if (optional.isPresent()) {
			if(depa.getUpDepa() != null && depa.getUpDepa().getId().equals( depa.getId() )) {
				depa.setUpDepa(optional.get().getUpDepa());
			}
			
			depaRepository.save(depa);
		}
		return flag;
	}

	@Override
	public List<Depa> listDepa() {
		return depaRepository.findAll();
	}

	@Override
	public Depa getDepa(Long id) {
		Depa depa = null;

		Optional<Depa> optional = depaRepository.findById(id);

		if (optional.isPresent()) {
			depa = optional.get();
		}

		return depa;
	}

	@Override
	public List<Depa> listDepaByKey(String key) {
		List<Depa> depas = new ArrayList<>();
		if("".equals(key)) {
			depas = listDepa();
		}else {
			depas = depaRepository.findByDepaNameLike("%" + key + "%");
		}
		return depas;
	}

	@Override
	public Page<Depa> listDepaByKey(String key, Pageable page) {
		return depaRepository.findByDepaNameLike("%" + key + "%", page);
	}
}
